//
//  SetViewController.m
//  记账本
//
//  Created by lirilu on 15/3/25.
//  Copyright (c) 2015年 glirlu@gmail.com. All rights reserved.
//

#import "MoreViewController.h"
#import "ArchiverData.h"
#import "Account.h"
#import "ArchiverData.h"
#import "ActiverTableViewCell.h"
#import "ShowArchivViewController.h"

@interface MoreViewController ()
@property(retain,nonatomic) NSMutableArray *PayModeArray;
@property(retain,nonatomic) NSMutableArray *archiveDataArray;
@property (weak, nonatomic) IBOutlet UITextField *archiveName;
@property (weak, nonatomic) IBOutlet UITableView *archiveTableView;
@property (weak, nonatomic) IBOutlet UIButton *addPayModeBtn;
@property (weak, nonatomic) IBOutlet UIButton *archiverBtn;
@end

@implementation MoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //添加监听器，监听输入框是否为空
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payModeNameTextChange) name:UITextFieldTextDidChangeNotification object:self.payModeName];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(archiveNameTextChange) name:UITextFieldTextDidChangeNotification object:self.archiveName];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)payModeNameTextChange{
    self.addPayModeBtn.enabled = self.payModeName.text.length?YES:NO;
}
- (void)archiveNameTextChange{
    self.archiverBtn.enabled = self.archiveName.text.length?YES:NO;
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([segue.identifier isEqualToString:@"MoreToShowArchive"]) {
        ShowArchivViewController *showArchiveVC = (ShowArchivViewController*)segue.destinationViewController;
        showArchiveVC.archiverData = (ArchiverData*)sender;
        showArchiveVC.title = ((ArchiverData*)sender).achiverFileName;
    }
    
}


- (NSMutableArray*)PayModeArray{
    if (!_PayModeArray) {
        //解档
        _PayModeArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[PayMode filePath]];
        if (!_PayModeArray) {
            _PayModeArray = [[NSMutableArray alloc]init];
        }
        
    }
    return _PayModeArray;
}

- (NSMutableArray *)archiveDataArray{
    if (!_archiveDataArray) {
        _archiveDataArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[ArchiverData filePath]];
        if (!_archiveDataArray) {
            _archiveDataArray = [[NSMutableArray alloc]init];
        }
    }
    return _archiveDataArray;
}

- (BOOL)copyAccountToFileName:(NSString*)fileName{
    if ([fileName isEqualToString:@"Account"] || [fileName length] == 0) {
        return NO;
    }
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    NSString *path = [docPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.data",fileName]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:[Account filePath]]) {
        NSError *error;
        if (![fileManager copyItemAtPath:[Account filePath] toPath:path error:&error]) {
            NSLog(@"%@",error);
            return NO;
        }else{
            return YES;
        }
    }
    return NO;
}

#pragma UITbaleViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ArchiverData *archiverData = self.archiveDataArray[indexPath.row];
    [self performSegueWithIdentifier:@"MoreToShowArchive" sender:archiverData];
}

#pragma UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.archiveDataArray count];
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ArchiverData *data = (ArchiverData*)self.archiveDataArray[indexPath.row];
    return [ActiverTableViewCell getCell:tableView ArchiverData:data];
}


#pragma mark btn
- (IBAction)AddBtnClick:(id)sender {
    if (self.payModeName.text != nil && [self.payModeName.text length] != 0) {
        PayMode *payMode = [[PayMode alloc]init];
        payMode.Name = self.payModeName.text;
        [self.PayModeArray addObject:payMode];
        //归档
        [NSKeyedArchiver archiveRootObject:self.PayModeArray toFile:[PayMode filePath]];
        self.payModeName.text = @"";
    }
}
- (IBAction)archivBtnTouchUpInside:(UIButton *)sender {
    if ([self.archivedDelegate respondsToSelector:@selector(archivedName:)]) {
        if ([self copyAccountToFileName:self.archiveName.text] == NO) {
            NSLog(@"erro");
        }else{
            ArchiverData * archiver = [[ArchiverData alloc]init];
            archiver.achiverFileName = self.archiveName.text;
            archiver.achiverDate = [NSDate date];
            archiver.outMoney = self.sumStru.outMoney;
            archiver.inMoney = self.sumStru.inMoney;
            [self.archiveDataArray insertObject:archiver atIndex:0];
            
            [NSKeyedArchiver archiveRootObject:self.archiveDataArray toFile:[ArchiverData filePath]];
            [self.archiveTableView reloadData];
            
            [self.archivedDelegate archivedName:self.archiveName.text];
            self.archiveName.text = @"";
        }
    }
}
@end
